<script setup>
import { ref, reactive, computed, watch, watchEffect, toRefs, shallowRef, shallowReactive, customRef, readonly, isRef, isReactive } from 'vue';
import Card from '@components/Common/Card.vue';

// 使用 ref 创建响应式基本类型
const count = ref(0);
const message = ref('Hello Vue 3!');

// 使用 reactive 创建响应式对象
const user = reactive({
  name: 'Vue开发者',
  level: 1,
  score: 0,
  skills: ['JavaScript', 'Vue'],
  profile: {
    bio: '热爱前端开发',
    joinDate: new Date()
  }
});

// 使用 toRefs 解构响应式对象
const { name, level, score } = toRefs(user);

// 使用 computed 创建计算属性
const doubleCount = computed(() => count.value * 2);
const userLevelText = computed(() => {
  if (user.level >= 5) return '专家级别';
  if (user.level >= 3) return '熟练级别';
  return '入门级别';
});
const fullScoreProgress = computed(() => (user.score / 50) * 100);

// 使用 watch 监听变化
let history = ref([]);
watch(count, (newVal, oldVal) => {
  history.value.push(`计数从 ${oldVal} 变为 ${newVal}`);
  // 限制历史记录长度
  if (history.value.length > 5) {
    history.value.shift();
  }
}, { immediate: true });

// 深度监听复杂对象
watch(() => user.profile, (newProfile, oldProfile) => {
  history.value.push(`用户简介已更新`);
}, { deep: true });

// 使用 watchEffect 自动追踪依赖
const effectLog = ref('');
let stopEffect = watchEffect((onCleanup) => {
  effectLog.value = `最新的消息: ${message.value} (计数: ${count.value})`;
  
  // 清理函数
  onCleanup(() => {
    console.log('副作用已清理');
  });
});

// 使用 shallowRef 和 shallowReactive
const shallowData = shallowRef({
  name: '浅响应式数据',
  nested: { value: 42 }
});

const shallowUser = shallowReactive({
  name: '浅响应式用户',
  settings: { theme: 'light' }
});

// 使用 customRef 创建自定义响应式引用
function useDebouncedRef(value, delay = 300) {
  let timeout;
  return customRef((track, trigger) => ({
    get() {
      track();
      return value;
    },
    set(newValue) {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        value = newValue;
        trigger();
      }, delay);
    }
  }));
}

const searchQuery = useDebouncedRef('');
const debounceLog = ref('');

watch(searchQuery, (newQuery) => {
  debounceLog.value = `搜索查询 (防抖后): "${newQuery}"`;
});

// 使用 readonly 创建只读响应式对象
const readonlyUser = readonly(user);

// 响应式状态检查
const isUserReactive = isReactive(user);
const isCountRef = isRef(count);

// 方法
const incrementCount = () => {
  count.value++;
  user.score += 10;
  if (user.score >= 50 && user.level < 5) {
    user.level++;
    user.score = 0;
    user.skills.push(`技能 ${user.level}`);
  }
};

const updateMessage = () => {
  message.value = `更新的消息: ${new Date().toLocaleTimeString()}`;
};

const updateUserProfile = () => {
  user.profile.bio = `更新的简介: ${new Date().toLocaleTimeString()}`;
};

const updateShallowData = () => {
  // 直接修改.value会触发更新
  shallowData.value.name = '更新后的名称';
  // 但嵌套属性不会触发更新
  shallowData.value.nested.value = Math.random();
};

const toggleShallowTheme = () => {
  // 直接属性会触发更新
  shallowUser.name = shallowUser.name === '浅响应式用户' ? '已更新用户' : '浅响应式用户';
  // 嵌套属性不会触发更新
  shallowUser.settings.theme = shallowUser.settings.theme === 'light' ? 'dark' : 'light';
};

const stopWatching = () => {
  stopEffect();
  effectLog.value = '副作用监听已停止';
};

const resetState = () => {
  count.value = 0;
  message.value = 'Hello Vue 3!';
  user.name = 'Vue开发者';
  user.level = 1;
  user.score = 0;
  user.skills = ['JavaScript', 'Vue'];
  user.profile.bio = '热爱前端开发';
  history.value = [];
  searchQuery.value = '';
  debounceLog.value = '';
  
  // 重新启动监听
  stopEffect = watchEffect((onCleanup) => {
    effectLog.value = `最新的消息: ${message.value} (计数: ${count.value})`;
    onCleanup(() => {
      console.log('副作用已清理');
    });
  });
};
</script>

<template>
  <div class="reactive-demo">
    <h2>Vue 3 响应式 API 演示</h2>
    
    <!-- 基础响应式 (ref) -->
  <Card title="基础响应式 (ref)" type="primary">
    <p>计数: {{ count }}</p>
    <p>计数的两倍: {{ doubleCount }}</p>
    <button @click="incrementCount">增加计数</button>
    <div class="status-info">
      <p>isCountRef: {{ isCountRef }}</p>
    </div>
  </Card>
    
    <!-- 对象响应式 (reactive) -->
  <Card title="对象响应式 (reactive)" type="secondary">
    <div class="user-info">
      <p>用户: {{ user.name }} (使用reactive)</p>
      <p>通过toRefs访问: {{ name.value }}</p>
      <p>等级: {{ user.level }} ({{ userLevelText }})</p>
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: fullScoreProgress + '%' }"></div>
      </div>
      <p>分数: {{ user.score }}/50</p>
      <div class="skills">
        <p>技能列表:</p>
        <span v-for="(skill, index) in user.skills" :key="index" class="skill-tag">{{ skill }}</span>
      </div>
    </div>
    <div class="status-info">
      <p>isUserReactive: {{ isUserReactive }}</p>
    </div>
  </Card>
    
    <!-- 嵌套对象响应式 -->
  <Card title="嵌套对象响应式">
    <p>用户简介: {{ user.profile.bio }}</p>
    <p>加入日期: {{ user.profile.joinDate.toLocaleDateString() }}</p>
    <button @click="updateUserProfile">更新简介</button>
  </Card>
    
    <!-- 消息更新 (ref) -->
  <Card title="消息更新 (ref)" type="success">
    <p>{{ message }}</p>
    <button @click="updateMessage">更新消息</button>
  </Card>
    
    <!-- 副作用追踪 (watchEffect) -->
  <Card title="副作用追踪 (watchEffect)">
    <p>{{ effectLog }}</p>
    <button @click="stopWatching">停止监听</button>
  </Card>
    
    <!-- 防抖搜索 (customRef) -->
  <Card title="自定义响应式引用 (customRef) - 防抖搜索" type="secondary">
    <input 
      v-model="searchQuery" 
      type="text" 
      placeholder="输入搜索内容 (300ms防抖)"
      class="search-input"
    />
    <p class="debounce-result">{{ debounceLog }}</p>
  </Card>
    
    <!-- 浅响应式演示 -->
  <Card title="浅响应式 (shallowRef)">
    <p>浅响应式数据名称: {{ shallowData.name }}</p>
    <p>嵌套属性值: {{ shallowData.nested.value }} <small>(修改不会触发更新)</small></p>
    <button @click="updateShallowData">更新浅响应式数据</button>
  </Card>
    
  <Card title="浅响应式对象 (shallowReactive)">
    <p>用户名: {{ shallowUser.name }}</p>
    <p>主题设置: {{ shallowUser.settings.theme }} <small>(修改不会触发更新)</small></p>
    <button @click="toggleShallowTheme">切换主题</button>
  </Card>
    
    <!-- 只读响应式 -->
  <Card title="只读响应式 (readonly)" type="secondary">
    <p>只读用户名称: {{ readonlyUser.name }}</p>
    <p>只读用户等级: {{ readonlyUser.level }}</p>
    <small>尝试修改将不会生效</small>
  </Card>
    
    <!-- 历史记录 (watch) -->
  <Card title="历史记录 (watch)">
    <ul class="history-list">
      <li v-for="(entry, index) in history" :key="index">{{ entry }}</li>
    </ul>
  </Card>
    
    <!-- 重置按钮 -->
  <Card title="" type="danger" shadow="false">
    <button class="reset-btn" @click="resetState">重置所有状态</button>
  </Card>
  </div>
</template>

<style scoped>
.reactive-demo {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
  font-size: 2rem;
  background: linear-gradient(45deg, #42b883, #35495e);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

h3 {
  color: #42b883;
  margin-bottom: 15px;
  font-size: 1.3rem;
  border-bottom: 2px solid #42b883;
  padding-bottom: 8px;
}

/* 保留demo-section的部分样式以确保兼容性 */
.demo-section {
  margin-bottom: 28px;
}

button {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 10px 18px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 10px;
  margin-bottom: 10px;
}

button:hover {
  background-color: #35495e;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

button:active {
  transform: translateY(0);
}

/* 用户信息区域 */
.user-info {
  margin-bottom: 15px;
}

/* 进度条样式 */
.progress-bar {
  width: 100%;
  height: 12px;
  background-color: #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
  margin: 12px 0;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #42b883, #63b3ed);
  border-radius: 6px;
  transition: width 0.3s ease;
}

/* 技能标签 */
.skills {
  margin-top: 15px;
}

.skill-tag {
  display: inline-block;
  background-color: #63b3ed;
  color: white;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 状态信息 */
.status-info {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
  font-size: 13px;
  color: #666;
}

/* 搜索输入框 */
.search-input {
  width: 100%;
  max-width: 400px;
  padding: 10px 15px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  margin-bottom: 15px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #42b883;
}

.debounce-result {
  color: #63b3ed;
  font-weight: 500;
  margin-top: 10px;
}

/* 历史记录列表 */
.history-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 120px;
  overflow-y: auto;
}

.history-list li {
  padding: 8px 12px;
  margin-bottom: 6px;
  background-color: #f0f0f0;
  border-radius: 6px;
  font-size: 14px;
  color: #555;
  border-left: 4px solid #42b883;
}

/* 重置按钮 */
.reset-btn {
  background-color: #ff6b6b;
  display: block;
  margin: 30px auto 0;
  padding: 14px 32px;
  font-size: 16px;
  font-weight: 600;
  min-width: 200px;
  border-radius: 30px;
}

.reset-btn:hover {
  background-color: #ff5252;
  box-shadow: 0 6px 12px rgba(255, 107, 107, 0.3);
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reactive-demo {
    padding: 15px;
  }
  
  .demo-section {
    padding: 18px;
    margin-bottom: 20px;
  }
  
  h2 {
    font-size: 1.8rem;
  }
  
  h3 {
    font-size: 1.2rem;
  }
  
  .search-input {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .demo-section {
    padding: 15px;
  }
  
  button {
    width: 100%;
    margin-right: 0;
  }
  
  .skill-tag {
    margin-right: 6px;
    padding: 3px 10px;
    font-size: 12px;
  }
}
</style>